<template>
  <div>
    <div class="row mb-1">
      <div class="col">
        <el-button @click="ActivityExcal4(false)" type="primary"
          >导出Excel</el-button
        >
        <el-button @click="ActivityExcal4(true)" type="primary"
          >导出Excel（含源码）</el-button
        >
        <el-button @click="start" type="primary">刷新</el-button>
        <span style="margin-left: 10px; color: #409eff; font-size: 14px;">
          💡 该页只展示提交过题目的学生成绩
        </span>
      </div>
      <div class="col text-right">
        <el-button >注册人数: {{ user.length }}</el-button>
        <el-button >有效人数: {{ usermatch.length }}</el-button>
        <el-button>判题中人数: {{ waitingCount + activeCount }}</el-button>
        <el-button >提交人数: {{ matchuserquestioncount }}</el-button>
      </div>
    </div>
    <div class="row mb-1">
      <div class="col">
        <el-table
          border
          :data="
            usermatch.slice(
              formquery._offset,
              formquery._offset + formquery._limit
            )
          "
          height="75vh"
          style="width: 100%"
        >
          <el-table-column type="expand">
            <template #default="props">
              <el-table
                border
                :data="props.row.matchuserquestion"
                style="width: 100%"
              >
                <el-table-column type="index" label="题目"></el-table-column>
                <el-table-column
                  prop="question.name"
                  label="题目名称"
                ></el-table-column>
                <el-table-column
                  prop="type"
                  width="100"
                  label="题目类型"
                ></el-table-column>
                <el-table-column prop="info" label="答案">
                  <template #default="scope">
                    <span v-if="scope.row.type === '判断'">{{
                      scope.row.info?.answer ? "正确" : "错误"
                    }}</span>
                    <span v-else>
                      {{ scope.row.info?.answer }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="df"
                  width="100"
                  label="得分"
                ></el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column prop="ID" label="用户ID"></el-table-column>
          <el-table-column prop="name" label="用户名"></el-table-column>
          <el-table-column prop="phonenum" label="手机"></el-table-column>
          <el-table-column prop="df" label="总分"></el-table-column>
          <!-- 新增审核状态列 -->
          <el-table-column
            v-if="activity?.questiontype === QuestionType.PUBLIC_TEST"
            prop="reviewStatus"
            label="审核(拍照题)"
            width="120"
          >
            <template #default="scope">
              <template
                v-if="getReviewStatus(scope.row) === ReviewStatus.REVIEWED"
              >
                <el-tag type="success" effect="plain">已审核</el-tag>
              </template>
              <template
                v-else-if="getReviewStatus(scope.row) === ReviewStatus.PENDING"
              >
                <el-button
                  type="danger"
                  plain
                  @click="gotoMatchQuestionCheck(activity?.ID!, scope.row.ID)"
                  >待审核</el-button
                >
              </template>
              <template v-else>
                <el-tag type="warning" effect="plain">未答题</el-tag>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            prop="updatedAt"
            :formatter="({ starttime }) => toLocaleDateString(starttime)"
            label="开始答题时间"
          ></el-table-column>
          <el-table-column
            prop="updatedAt"
            :formatter="({ endtime }) => toLocaleDateString(endtime)"
            label="交卷时间"
          >
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button
                type="danger"
                @click="deluserquestion(scope.row.ID, Number(activity?.ID))"
                size="default"
                >删除答题</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-pagination
      class="pager"
      @current-change="handleCurrentChange"
      :page-size="Number(formquery._limit)"
      layout="prev, pager, next"
      :total="usermatch.length"
    ></el-pagination>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { computed, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import {
  asyncdelmatchuserquestion,
  asyncgetmatchjob,
  asyncselectmatchuserquestion,
} from "../../../api";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { QuestionType } from "../../../util/data";
import { getExceltodownload2 } from "../../../util/excel";
import { toLocaleDateString } from "../../../util/time";
import { groupBy } from "underscore";

const router = useRouter();

const p = defineProps<{ data: Studycodemodel.Iactivity }>();

const formquery = reactive({
  _limit: 30,
  _offset: 0,
});

function handleCurrentChange(val: number) {
  formquery._offset = Number(formquery._limit) * (val - 1);
}

const matchuserquestion = ref<Studycodemodel.Imatchuserquestion[]>([]);
const user = ref<Studycodemodel.Iuser[]>([]);
const question = ref<Studycodemodel.Iquestion[]>([]);
const activity = ref<Studycodemodel.Iactivity>();

interface matchuserquestionView extends Studycodemodel.Iuser {
  df: number;
  starttime: Date;
  endtime: Date;
  reviewStatus?: string; // 新增字段
}

const usermatch = computed<matchuserquestionView[]>(() => {
  const submittedUserIds = new Set(matchuserquestion.value.map((q) => q.userid));
  return user.value
    .filter((u) => submittedUserIds.has(u.ID))
    .map((e) => {
      const _matchuserquestion = matchuserquestion.value
        .filter((n) => n.userid === e.ID)
        .map((n) => {
          const _question = question.value.find((t) => t.ID === n.questionid);
          return {
            ...n,
            question: _question,
          };
        });

      const { _df, starttime, endtime } = _matchuserquestion.reduce(
        (acc, item) => {
          const { df = 0, createdAt = new Date() } = item;
          const currentTime = new Date(createdAt);

          return {
            _df: acc._df + df,
            starttime:
              currentTime < acc.starttime ? currentTime : acc.starttime,
            endtime: currentTime > acc.endtime ? currentTime : acc.endtime,
          };
        },
        {
          _df: 0,
          starttime: new Date(),
          endtime: new Date(0), // 使用最小日期作为初始值
        }
      );

      return {
        ...e,
        matchuserquestion: _matchuserquestion,
        df: _df,
        starttime,
        endtime,
      };
    })
    .sort((a, b) => b.df - a.df);
});

// 审核状态枚举
const ReviewStatus = {
  REVIEWED: "reviewed", // 已审核
  PENDING: "pending", // 待审核
  NONE: "none", // 无拍照题或未答题
} as const;
// 审核状态判断函数
const getReviewStatus = (row: matchuserquestionView) => {
  // 获取用户的所有拍照题
  const photoQuestions = (row.matchuserquestion || []).filter(
    (q) => q.type === "拍照"
  );

  // 如果没有拍照题，返回NONE
  if (photoQuestions.length === 0) {
    return ReviewStatus.NONE;
  }

  // 检查是否有未审核的拍照题（resultdata为空）
  const hasUnreviewed = photoQuestions.some((q) => !q.resultdata);

  return hasUnreviewed ? ReviewStatus.PENDING : ReviewStatus.REVIEWED;
};

function ActivityExcal4(usecontext: boolean) {
  const q = question.value.map((e, k) => `第${k + 1}题`);
  const questionCount = question.value.length;

  // 预处理团队数据映射
  const userTeamMap = new Map<number, { teams: string; teamType: string }>();
  const key = ["团员", "管理员", "教师"];
  console.log(21213213)
  // 只处理有提交记录的用户
  const usersWithSubmissions = usermatch.value;
  
  usersWithSubmissions.forEach((u) => {
    const userTeams = teamuser.value
      .filter((tu) => tu.userid === u.ID)
      .map((tu) => {
        const team1 = team.value.find((t) => t.ID === tu.teamid);
        return { name: team1?.name || "", isAdmin: tu.isAdmin };
      });

    const teams = userTeams
      .map((t) => t.name)
      .filter(Boolean)
      .join(",");
    const teamType =
      userTeams.length > 0
        ? key[Math.max(...userTeams.map((t) => t.isAdmin!))] || "管理员"
        : "管理员";

    userTeamMap.set(u.ID!, { teams, teamType });
  });

  // 预处理用户答题数据映射
  const userQuestionsMap = new Map<number, any[]>();
  matchuserquestion.value.forEach((muq) => {
    if (!userQuestionsMap.has(muq.userid!)) {
      userQuestionsMap.set(muq.userid!, []);
    }
    userQuestionsMap.get(muq.userid!)!.push(muq);
  });

  const sheet1: any[][] = [];
  const sheet2: any[][] = [];
  const sheet4: any[][] = [];
  const ather: any[][] = [];

  // 初始化统计数组
  const scoreStats = {
    all: 0,
    all1: new Array(questionCount).fill(0), // 100分
    all2: new Array(questionCount).fill(0), // 71-99分
    all3: new Array(questionCount).fill(0), // 20-70分
    all4: new Array(questionCount).fill(0), // 1-19分
    all5: new Array(questionCount).fill(0), // 0分
  };

  // 主循环：一次遍历处理所有数据
  usersWithSubmissions.forEach((user) => {
    const { ID, name, xingming, phonenum, info } = user;
    const userquestions = userQuestionsMap.get(ID!) || [];

    if (userquestions.length === 0) return;

    scoreStats.all++;
    const teamInfo = userTeamMap.get(ID!) || { teams: "", teamType: "管理员" };

    // 计算总分
    const totalScore = userquestions.reduce((sum, uq) => sum + (uq.df || 0), 0);

    // 构建基础行数据
    const baseRow = [
      name,
      xingming,
      teamInfo.teams,
      ID,
      phonenum,
      info?.school,
      info?.grade,
      info?.class,
      teamInfo.teamType,
      totalScore,
    ];

    const t1 = [...baseRow];
    const t2 = [...baseRow];
    const t4 = [...baseRow];

    // 按题目顺序处理答案
    question.value.forEach((question, index) => {
      const userquestion =
        userquestions.find((uq) => uq.questionid === question.ID) || {};
      const {
        df = 0,
        resultdataarr = [],
        resultdata = "CE",
        context,
        type,
        info: answerInfo,
      } = userquestion;

      // 统计得分段
      if (df === 100) {
        scoreStats.all1[index]++;
      } else if (df > 70) {
        scoreStats.all2[index]++;
      } else if (df > 19) {
        scoreStats.all3[index]++;
      } else if (df > 0) {
        scoreStats.all4[index]++;
      } else {
        scoreStats.all5[index]++;
      }

      // 添加到各个sheet
      t1.push(df);
      t4.push(context?.slice(0, 30000));

      if (type === "代码") {
        if (resultdata === "CE" || !context || !resultdata) {
          t2.push("Compile Error");
        } else {
          t2.push(`${df} (${resultdataarr.join(",")})`);
        }
      } else {
        t2.push(`${df} (${(answerInfo as any)?.answer || ""})`);
      }
    });

    sheet1.push(t1);
    sheet2.push(t2);
    sheet4.push(t4);
  });

  // 构建统计数据
  const { all, all1, all2, all3, all4, all5 } = scoreStats;
  const getPercentage = (count: number) =>
    Math.floor((count / all) * 10000) / 100 + "%";

  const tj = [
    ["题目得分段统计", ...q],
    ["100%分段", ...all1.map(getPercentage)],
    ["71%-99%分段", ...all2.map(getPercentage)],
    ["20%-70%分段", ...all3.map(getPercentage)],
    ["1%-19%分段", ...all4.map(getPercentage)],
    ["0分段", ...all5.map(getPercentage)],
    [],
    [],
    [],
    ["有效参赛人员占比", Math.floor((all / usersWithSubmissions.length) * 10000) / 100 + "%"],
    ["总注册人员占比", Math.floor((all / user.value.length) * 10000) / 100 + "%"],
  ];

  const headers = [
    "昵称",
    "姓名",
    "团队",
    "ID",
    "手机号",
    "学校",
    "年级",
    "班级",
    "团队角色",
    "总得分",
    ...q,
  ];

  const dowm: Record<string, any[][]> = {
    得分统计: [headers, ...sheet1.sort((a, b) => b[8] - a[8]), ...ather],
    得分点: [headers, ...sheet2.sort((a, b) => b[8] - a[8]), ...ather],
    分段统计: tj,
  };

  if (usecontext) {
    dowm.代码 = [headers, ...sheet4.sort((a, b) => b[8] - a[8]), ...ather];
  }

  getExceltodownload2(dowm, p.data.name || "");
}

onMounted(() => {
  start();
});

const team = ref<Studycodemodel.Iteam[]>([]);
const teamuser = ref<Studycodemodel.Iteamuser[]>([]);

const matchuserquestioncount = computed(() => {
  const obj = groupBy(matchuserquestion.value, "userid");
  return Object.keys(obj).length;
});

const waitingCount = ref(0)
const activeCount = ref(0)

async function start() {
  if (p.data.ID) {
    const data = await asyncselectmatchuserquestion({ ID: p.data.ID });
    matchuserquestion.value = data.userquestion;
    user.value = data.user;
    question.value = data.question;
    activity.value = data.activity;
    team.value = data.team;
    teamuser.value = data.teamuser;
    const d = await asyncgetmatchjob({ activityid: p.data.ID })
    waitingCount.value = d.waitingCount || 0
    activeCount.value = d.activeCount || 0
  }
}

async function deluserquestion(ID: number, activityid: number) {
  if (ID) {
    ElMessageBox.confirm("是否删除该选项, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "error",
    }).then(async () => {
      try {
        await asyncdelmatchuserquestion({ userid: ID, activityid });
        ElMessage.success("删除成功");
        start();
      } catch (e: any) {
        ElMessage.info("删除成功");
      }
    });
  } else {
    ElMessage.warning("没有找到此用户");
  }
}

function gotoMatchQuestionCheck(activityId: number, userId: number) {
  // 新开标签页跳转到 matchQuestionCheck 页面，带上 activityId 和 userId
  const url = router.resolve({
    path: "/matchQuestionCheck",
    query: { activityId, userId },
  }).href;
  window.open(url, "_blank");
}
</script>
